package de.breitbeil.jbooking.ui.dataview.columns;

import java.awt.Component;
import java.util.Comparator;
import java.util.Locale;

import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;

import org.springframework.context.ApplicationContext;
import org.springframework.richclient.application.Application;
import org.springframework.util.comparator.NullSafeComparator;

public class I18NDataViewColumn extends DataViewColumnImpl {

    public I18NDataViewColumn(String property) { 
        super(property);
        
        I18NTableCellRenderer renderer = new I18NTableCellRenderer();
        setCellRenderer(renderer);
        setComparator(renderer);
    }
    
    protected class I18NTableCellRenderer extends DefaultTableCellRenderer implements Comparator<Object> {

        private Comparator<Object> comparator = new NullSafeComparator(String.CASE_INSENSITIVE_ORDER, false);
        private ApplicationContext context;
        
        public I18NTableCellRenderer() {
            context = Application.instance().getApplicationContext();
        }
        
        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
            super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
            setText(getString(value));
            return this;
        }
        
        public String getString(Object item) {
            if(item == null) {
                return "";
            }
            
            String i18n = context.getMessage(item.toString()+".label", new String[0], Locale.getDefault()); 
            return i18n;
        }
        
        public int compare(Object o1, Object o2) {
            return comparator.compare(getString(o1), getString(o2));
        }
    }
}
